package cn.sunxyz.core.bean;

import cn.sunxyz.common.utils.reflect.ClassUtil;

import java.lang.annotation.Annotation;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by yangrd on 2017/5/19.
 */
class DefaultClassContainer implements ClassContainer {

    private Collection<Class<?>> classCollection;

    public DefaultClassContainer(Collection<Class<?>> classCollection) {
        this.classCollection = classCollection;
    }

    @Override
    public List<Class<?>> listClassByAnnotation(Class<? extends Annotation> annotationClass) {
        return classCollection.stream().filter(cls -> isAnnotationPresent(cls, annotationClass)).collect(Collectors.toList());
    }

    @Override
    public List<Class<?>> listClassBySuper(Class<?> superClass) {
        return classCollection.stream().filter(cls -> superClass.isAssignableFrom(cls) && !superClass.equals(cls)).collect(Collectors.toList());
    }

    /**
     * 递归Class所有的Annotation，一个最彻底的实现.
     * 包括所有基类，所有接口的Annotation，同时支持Spring风格的Annotation继承的父Annotation，
     */
    private boolean isAnnotationPresent(Class<?> cls, Class<? extends Annotation> annotationClass) {
        return ClassUtil.getAllAnnotations(cls).stream().map(Annotation::annotationType).collect(Collectors.toSet()).contains(annotationClass);
    }

}
